const MenuItem = require('../models/MenuItem');
const MenuCategory = require('../models/MenuCategory');
const { validationResult } = require('express-validator');
const path = require('path');
const fs = require('fs');
const multer = require('multer');
const sharp = require('sharp');
const { query: dbQuery, pool } = require('../config/database');
const { logger } = require('../utils/logger');
// 图片上传配置
const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
const ALLOWED_FORMATS = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];

// ============ Admin↔Model 字段映射辅助函数 ============
function normalizeTagsObject(tags) {
  try {
    if (!tags) return {};
    if (typeof tags === 'string') return JSON.parse(tags);
    if (typeof tags === 'object') return { ...tags };
    return {};
  } catch (e) {
    return {};
  }
}

function mapAdminBodyToModel(body = {}) {
  const data = { ...body };

  // category: { value } → category_id
  if (!data.category_id && data.category && typeof data.category === 'object') {
    const v = data.category.value ?? data.category.id;
    if (v !== undefined) data.category_id = parseInt(v, 10);
  }

  // image → image_url
  if (!data.image_url && typeof data.image === 'string') {
    data.image_url = data.image;
  }
  // imageUrl → image_url（兼容别名）
  if (!data.image_url && typeof data.imageUrl === 'string') {
    data.image_url = data.imageUrl;
  }

  // isHot → is_featured
  if (Object.prototype.hasOwnProperty.call(data, 'isHot')) {
    data.is_featured = data.isHot === true || data.isHot === 'true';
  }

  // originalPrice / original_price, stock, status, isNew 存入 tags._admin
  const existingTags = normalizeTagsObject(data.tags);
  const adminMeta = { ...(existingTags._admin || {}) };

  if (Object.prototype.hasOwnProperty.call(data, 'originalPrice')) {
    adminMeta.originalPrice = data.originalPrice;
  } else if (Object.prototype.hasOwnProperty.call(data, 'original_price')) {
    adminMeta.originalPrice = data.original_price;
  }

  if (Object.prototype.hasOwnProperty.call(data, 'stock')) {
    adminMeta.stock = data.stock;
  }

  let statusHidden;
  if (typeof data.status === 'object' && data.status) {
    if (Object.prototype.hasOwnProperty.call(data.status, 'hidden')) {
      statusHidden = data.status.hidden === true || data.status.hidden === 'true';
    }
  } else if (typeof data.status === 'string') {
    statusHidden = data.status.toLowerCase() === 'hidden';
  }
  if (statusHidden !== undefined) {
    adminMeta.status = { ...(adminMeta.status || {}), hidden: !!statusHidden };
  }

  if (Object.prototype.hasOwnProperty.call(data, 'isNew')) {
    adminMeta.isNew = data.isNew === true || data.isNew === 'true';
  }

  const mergedTags = { ...existingTags, _admin: adminMeta };
  if (Object.keys(mergedTags).length > 0) {
    data.tags = mergedTags;
  }

  return data;
}

async function attachAdminComputedFields(item, lang = 'zh') {
  if (!item) return item;
  const src = typeof item.toJSON === 'function' ? item.toJSON() : (typeof item === 'object' ? { ...item } : item);
  const tagsObj = normalizeTagsObject(src.tags);
  const meta = tagsObj._admin || {};

  // 查询肉类选择
  let meatSelections = ['', '', ''];
  try {
    if (src.id) {
      const meatOptions = await dbQuery(
        'SELECT option_name FROM menu_options WHERE menu_item_id = ? AND option_group = "Meat" AND deleted_at IS NULL ORDER BY sort_order',
        [src.id]
      );
      meatSelections = [
        meatOptions[0]?.option_name || '',
        meatOptions[1]?.option_name || '',
        meatOptions[2]?.option_name || ''
      ];
    }
  } catch (error) {
    // 如果查询失败，使用默认空值
    console.warn('Failed to fetch meat selections:', error);
  }

  return {
    ...src,
    // 根据语言返回相应的名称和描述
    name: lang === 'en' ? (src.name_en || src.name) : src.name,
    description: lang === 'en' ? (src.description_en || src.description) : src.description,
    ingredients: lang === 'en' ? (src.main_ingredients_en || src.main_ingredients) : src.main_ingredients,
    category: { value: src.category_id },
    image: src.image_url || null,
    isHot: !!src.is_featured,
    isNew: !!meta.isNew,
    originalPrice: meta.originalPrice ?? null,
    stock: meta.stock ?? null,
    // 正确映射数据库is_available字段到前端status字符串
    status: (() => {
      // 如果meta中有status配置且为hidden，返回hidden
      if (meta.status && meta.status.hidden === true) {
        return 'hidden';
      }
      // 否则根据数据库is_available字段决定
      return src.is_available ? 'available' : 'unavailable';
    })(),
    // 添加用户需要的字段
    main_ingredients: lang === 'en' ? (src.main_ingredients_en || src.main_ingredients || '') : (src.main_ingredients || ''),
    main_ingredients_en: src.main_ingredients_en || '',
    quantity_selection: src.quantity_selection || '',
    normalized_name: src.normalized_name || '',
    is_recommended: !!src.is_recommended,
    is_spicy: !!src.is_spicy,
    is_vegetarian: !!src.is_vegetarian,
    is_vegan: !!src.is_vegan,
    is_gluten_free: !!src.is_gluten_free,
    // 肉类选择字段
    meat_selection_1: meatSelections[0],
    meat_selection_2: meatSelections[1],
    meat_selection_3: meatSelections[2]
  };
}

// 文件过滤器 - 验证图片格式和大小
const fileFilter = (req, file, cb) => {
  // 检查文件类型
  if (!ALLOWED_FORMATS.includes(file.mimetype)) {
    return cb(new Error('不支持的图片格式。请上传 JPG, PNG, GIF 或 WebP 格式的图片。'), false);
  }
  cb(null, true);
};

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // 修改存储路径，与静态文件服务配置匹配
    const uploadDir = path.join(__dirname, '../../uploads/menu-images');
    // 确保目录存在
    try {
      if (!fs.existsSync(uploadDir)) {
        logger.debug(`[uploadItemImage] 创建上传目录: ${uploadDir}`);
        fs.mkdirSync(uploadDir, { recursive: true });
      }
      cb(null, uploadDir);
    } catch (error) {
      logger.error(`[uploadItemImage] 创建上传目录失败:`, error);
      cb(new Error('无法创建上传目录'));
    }
  },
  filename: function (req, file, cb) {
    // 统一使用png格式保存
    const filename = `menu_${Date.now()}_${Math.round(Math.random() * 1E9)}.png`;
    cb(null, filename);
  }
});

const upload = multer({ 
  storage, 
  fileFilter,
  limits: { fileSize: MAX_FILE_SIZE }
});

/**
 * 菜单管理控制器
 */
class MenuController {
  /**
   * 获取所有菜单分类
   */
  static async getCategories(req, res) {
    try {
      const { is_active } = req.query;
      const options = {};
      
      if (is_active !== undefined) {
        options.is_active = is_active === 'true';
      }

      const categories = await MenuCategory.findAll(options);
      
      res.json({
        success: true,
        data: categories,
        message: '获取菜单分类成功'
      });
    } catch (error) {
      logger.error('获取菜单分类失败:', error);
      res.status(500).json({
        success: false,
        message: '获取菜单分类失败',
        error: error.message
      });
    }
  }

  /**
   * 获取分类及其菜单项数量
   */
  static async getCategoriesWithCount(req, res) {
    try {
      const categories = await MenuCategory.getCategoriesWithItemCount();
      
      res.json({
        success: true,
        data: categories,
        message: '获取分类统计成功'
      });
    } catch (error) {
      logger.error('获取分类统计失败:', error);
      res.status(500).json({
        success: false,
        message: '获取分类统计失败',
        error: error.message
      });
    }
  }

  /**
   * 创建菜单分类
   */
  static async createCategory(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败',
          errors: errors.array()
        });
      }

      const category = await MenuCategory.create(req.body);
      
      res.status(201).json({
        success: true,
        data: category,
        message: '创建菜单分类成功'
      });
    } catch (error) {
      logger.error('创建菜单分类失败:', error);
      res.status(500).json({
        success: false,
        message: '创建菜单分类失败',
        error: error.message
      });
    }
  }

  /**
   * 更新菜单分类
   */
  static async updateCategory(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败',
          errors: errors.array()
        });
      }

      const { id } = req.params;
      const category = await MenuCategory.update(id, req.body);
      
      if (!category) {
        return res.status(404).json({
          success: false,
          message: '菜单分类不存在'
        });
      }

      res.json({
        success: true,
        data: category,
        message: '更新菜单分类成功'
      });
    } catch (error) {
      logger.error('更新菜单分类失败:', error);
      res.status(500).json({
        success: false,
        message: '更新菜单分类失败',
        error: error.message
      });
    }
  }

  /**
   * 删除菜单分类
   */
  static async deleteCategory(req, res) {
    try {
      const { id } = req.params;
      const success = await MenuCategory.delete(id);
      
      if (!success) {
        return res.status(404).json({
          success: false,
          message: '菜单分类不存在或删除失败'
        });
      }

      res.json({
        success: true,
        message: '删除菜单分类成功'
      });
    } catch (error) {
      logger.error('删除菜单分类失败:', error);
      res.status(500).json({
        success: false,
        message: '删除菜单分类失败',
        error: error.message
      });
    }
  }

  /**
   * 批量更新分类排序
   */
  static async updateCategoriesSort(req, res) {
    try {
      const { categories } = req.body;
      
      if (!Array.isArray(categories)) {
        return res.status(400).json({
          success: false,
          message: '分类数据格式错误'
        });
      }

      await MenuCategory.updateSortOrder(categories);
      
      res.json({
        success: true,
        message: '更新分类排序成功'
      });
    } catch (error) {
      logger.error('更新分类排序失败:', error);
      res.status(500).json({
        success: false,
        message: '更新分类排序失败',
        error: error.message
      });
    }
  }

  /**
   * 获取菜单项列表
   */
  static async getMenuItems(req, res) {
    try {
      const {
        category_id,
        is_available,
        search,
        page = 1,
        limit = 20,
        sort_by = 'sort_order',
        sort_order = 'ASC',
        lang = 'zh' // 添加语言参数支持
      } = req.query;

      const options = {
        page: parseInt(page),
        limit: parseInt(limit),
        sort_by,
        sort_order
      };

      if (category_id) options.category_id = category_id;
      if (is_available !== undefined) options.is_available = is_available === 'true';
      if (search) options.search = search;

      const menuItems = await MenuItem.findAll(options);

      // 适配 Admin 所需别名字段并根据语言返回相应字段
      const adaptedItems = Array.isArray(menuItems.items)
        ? await Promise.all(menuItems.items.map(item => attachAdminComputedFields(item, lang)))
        : [];
      
      const adapted = {
        ...menuItems,
        items: adaptedItems
      };
      
      res.json({
        success: true,
        data: adapted,
        message: lang === 'en' ? 'Menu items retrieved successfully' : '获取菜单项成功'
      });
    } catch (error) {
      logger.error('获取菜单项失败:', error);
      res.status(500).json({
        success: false,
        message: '获取菜单项失败',
        error: error.message
      });
    }
  }

  /**
   * 根据分类获取菜单项
   */
  static async getMenuItemsByCategory(req, res) {
    try {
      const { categoryId } = req.params;
      const { is_available } = req.query;
      
      const options = { category_id: categoryId };
      if (is_available !== undefined) {
        options.is_available = is_available === 'true';
      }

      const menuItems = await MenuItem.findAll(options);

      const adaptedItems = Array.isArray(menuItems.items)
        ? await Promise.all(menuItems.items.map(attachAdminComputedFields))
        : [];
      
      const adapted = {
        ...menuItems,
        items: adaptedItems
      };
      
      res.json({
        success: true,
        data: adapted,
        message: '获取分类菜单项成功'
      });
    } catch (error) {
      logger.error('获取分类菜单项失败:', error);
      res.status(500).json({
        success: false,
        message: '获取分类菜单项失败',
        error: error.message
      });
    }
  }

  /**
   * 获取菜单项详情
   */
  static async getMenuItem(req, res) {
    try {
      const { id } = req.params;
      const menuItem = await MenuItem.findById(id);
      
      if (!menuItem) {
        return res.status(404).json({
          success: false,
          message: '菜单项不存在'
        });
      }

      const adaptedMenuItem = await attachAdminComputedFields(menuItem);
      
      res.json({
        success: true,
        data: adaptedMenuItem,
        message: '获取菜单项详情成功'
      });
    } catch (error) {
      logger.error('获取菜单项详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取菜单项详情失败',
        error: error.message
      });
    }
  }

  /**
   * 创建菜单项
   */
  static async createMenuItem(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败',
          errors: errors.array()
        });
      }

      const mapped = mapAdminBodyToModel(req.body);
      const menuItem = await MenuItem.create(mapped);
      
      res.status(201).json({
        success: true,
        data: attachAdminComputedFields(menuItem),
        message: '创建菜单项成功'
      });
    } catch (error) {
      logger.error('创建菜单项失败:', error);
      res.status(500).json({
        success: false,
        message: '创建菜单项失败',
        error: error.message
      });
    }
  }

  /**
   * 更新菜单项
   */
  static async updateMenuItem(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败',
          errors: errors.array()
        });
      }

      const { id } = req.params;
      const mapped = mapAdminBodyToModel(req.body);
      const menuItem = await MenuItem.update(id, mapped);
      
      if (!menuItem) {
        return res.status(404).json({
          success: false,
          message: '菜单项不存在'
        });
      }

      res.json({
        success: true,
        data: attachAdminComputedFields(menuItem),
        message: '更新菜单项成功'
      });
    } catch (error) {
      logger.error('更新菜单项失败:', error);
      res.status(500).json({
        success: false,
        message: '更新菜单项失败',
        error: error.message
      });
    }
  }

  /**
   * 删除菜单项
   */
  static async deleteMenuItem(req, res) {
    try {
      const { id } = req.params;
      const success = await MenuItem.delete(id);
      
      if (!success) {
        return res.status(404).json({
          success: false,
          message: '菜单项不存在或删除失败'
        });
      }

      res.json({
        success: true,
        message: '删除菜单项成功'
      });
    } catch (error) {
      logger.error('删除菜单项失败:', error);
      res.status(500).json({
        success: false,
        message: '删除菜单项失败',
        error: error.message
      });
    }
  }

  /**
   * 更新菜单项可用性
   */
  static async updateAvailability(req, res) {
    try {
      const { id } = req.params;
      const { is_available } = req.body;
      
      const success = await MenuItem.updateAvailability(id, is_available);
      
      if (!success) {
        return res.status(404).json({
          success: false,
          message: '菜单项不存在'
        });
      }

      res.json({
        success: true,
        message: '更新菜单项可用性成功'
      });
    } catch (error) {
      logger.error('更新菜单项可用性失败:', error);
      res.status(500).json({
        success: false,
        message: '更新菜单项可用性失败',
        error: error.message
      });
    }
  }

  /**
   * 批量更新菜单项排序
   */
  static async updateMenuItemsSort(req, res) {
    try {
      const { items } = req.body;
      
      if (!Array.isArray(items)) {
        return res.status(400).json({
          success: false,
          message: '菜单项数据格式错误'
        });
      }

      await MenuItem.updateSortOrder(items);
      
      res.json({
        success: true,
        message: '更新菜单项排序成功'
      });
    } catch (error) {
      logger.error('更新菜单项排序失败:', error);
      res.status(500).json({
        success: false,
        message: '更新菜单项排序失败',
        error: error.message
      });
    }
  }

  /**
   * 搜索菜单项
   */
  static async searchMenuItems(req, res) {
    try {
      const { q: query, category_id, is_available } = req.query;
      
      if (!query || query.trim().length === 0) {
        return res.status(400).json({
          success: false,
          message: '搜索关键词不能为空'
        });
      }

      const options = { search: query.trim() };
      if (category_id) options.category_id = category_id;
      if (is_available !== undefined) options.is_available = is_available === 'true';

      const menuItems = await MenuItem.search(options);

      const adaptedItems = Array.isArray(menuItems.items)
        ? await Promise.all(menuItems.items.map(attachAdminComputedFields))
        : [];
      
      const adapted = {
        ...menuItems,
        items: adaptedItems
      };
      
      res.json({
        success: true,
        data: adapted,
        message: '搜索菜单项成功'
      });
    } catch (error) {
      logger.error('搜索菜单项失败:', error);
      res.status(500).json({
        success: false,
        message: '搜索菜单项失败',
        error: error.message
      });
    }
  }

  /**
   * 获取热门菜品
   */
  static async getPopularItems(req, res) {
    try {
      const { limit = 10, days = 30 } = req.query;
      
      const endDate = new Date();
      const startDate = new Date();
      startDate.setDate(startDate.getDate() - parseInt(days));

      const popularItems = await MenuItem.getPopularItems({
        start_date: startDate,
        end_date: endDate,
        limit: parseInt(limit)
      });

      let data;
      if (Array.isArray(popularItems)) {
        data = popularItems.map(attachAdminComputedFields);
      } else if (popularItems && Array.isArray(popularItems.items)) {
        data = { ...popularItems, items: popularItems.items.map(attachAdminComputedFields) };
      } else {
        data = popularItems;
      }
      
      res.json({
        success: true,
        data,
        message: '获取热门菜品成功'
      });
    } catch (error) {
      logger.error('获取热门菜品失败:', error);
      res.status(500).json({
        success: false,
        message: '获取热门菜品失败',
        error: error.message
      });
    }
  }

  /**
   * 获取推荐菜品
   */
  static async getRecommendedItems(req, res) {
    try {
      const { limit = 10 } = req.query;
      
      const recommendedItems = await MenuItem.getRecommended(parseInt(limit));

      let data;
      if (Array.isArray(recommendedItems)) {
        data = await Promise.all(recommendedItems.map(attachAdminComputedFields));
      } else if (recommendedItems && Array.isArray(recommendedItems.items)) {
        const adaptedItems = await Promise.all(recommendedItems.items.map(attachAdminComputedFields));
        data = { ...recommendedItems, items: adaptedItems };
      } else {
        data = recommendedItems;
      }
      
      res.json({
        success: true,
        data,
        message: '获取推荐菜品成功'
      });
    } catch (error) {
      logger.error('获取推荐菜品失败:', error);
      res.status(500).json({
        success: false,
        message: '获取推荐菜品失败',
        error: error.message
      });
    }
  }

  /**
   * 获取完整菜单（分类+菜品）
   */
  static async getFullMenu(req, res) {
    try {
      const { is_available } = req.query;
      
      // 获取活跃的分类
      const categories = await MenuCategory.getActive();
      
      // 为每个分类获取菜品
      const menuData = await Promise.all(
        categories.map(async (category) => {
          const options = { 
            category_id: category.id,
            sort_by: 'sort_order',
            sort_order: 'ASC'
          };
          
          if (is_available !== undefined) {
            options.is_available = is_available === 'true';
          }
          
          const items = await MenuItem.findAll(options);
          const adaptedItems = Array.isArray(items.items)
            ? await Promise.all(items.items.map(attachAdminComputedFields))
            : [];
          
          return {
            ...category,
            items: adaptedItems
          };
        })
      );
      
      res.json({
        success: true,
        data: menuData,
        message: '获取完整菜单成功'
      });
    } catch (error) {
      logger.error('获取完整菜单失败:', error);
      res.status(500).json({
        success: false,
        message: '获取完整菜单失败',
        error: error.message
      });
    }
  }

  /**
   * 排序分类（别名方法）
   */
  static async sortCategories(req, res) {
    return MenuController.updateCategoriesSort(req, res);
  }

  /**
   * 排序菜单项（别名方法）
   */
  static async sortMenuItems(req, res) {
    return MenuController.updateMenuItemsSort(req, res);
  }

  static uploadItemImage = [
    upload.single('image'),
    async (req, res) => {
      try {
        const { id } = req.params;
        logger.debug(`[uploadItemImage] 接收到菜单项 ID: ${id} 的图片上传请求`);
        
        if (!req.file) {
          logger.debug(`[uploadItemImage] 错误: 未收到图片文件`);
          return res.status(400).json({
            success: false,
            message: '未收到图片文件'
          });
        }
        
        logger.debug(`[uploadItemImage] 文件信息:`, {
          filename: req.file.filename,
          originalname: req.file.originalname,
          path: req.file.path,
          size: req.file.size,
          mimetype: req.file.mimetype
        });
        
        // 使用Sharp处理图片 - 统一转换为PNG格式
        try {
          const outputFilename = req.file.filename;
          const outputPath = req.file.path;
          
          // 使用sharp处理图片 - 调整大小并转换为PNG格式
          await sharp(req.file.path)
            .resize(800, 800, { fit: 'inside', withoutEnlargement: true }) // 限制最大尺寸
            .png({ quality: 90 }) // 转换为PNG格式，质量90%
            .toFile(outputPath + '.tmp');
          
          // 替换原文件
          fs.unlinkSync(req.file.path);
          fs.renameSync(outputPath + '.tmp', outputPath);
          
          logger.debug(`[uploadItemImage] 图片处理成功: ${outputPath}`);
        } catch (sharpError) {
          logger.error(`[uploadItemImage] 图片处理失败:`, sharpError);
          return res.status(500).json({
            success: false,
            message: '图片处理失败'
          });
        }
        
        logger.debug(`[uploadItemImage] 生成的图片URL: ${imageUrl}`);
        
        // 2. 验证菜单项是否存在
        logger.debug(`[uploadItemImage] 检查菜单项 ID ${id} 是否存在`);
        const menuItem = await MenuItem.findById(id);
        logger.debug(`[uploadItemImage] 菜单项查询结果:`, menuItem ? `找到ID为${id}的菜单项` : `未找到ID为${id}的菜单项`);
        
        if (!menuItem) {
          logger.debug(`[uploadItemImage] 错误: 菜单项 ID ${id} 不存在或已被删除`);
          // 删除已上传的文件
          logger.debug(`[uploadItemImage] 删除已上传的图片: ${req.file.path}`);
          try {
            fs.unlinkSync(req.file.path);
          } catch (unlinkErr) {
            logger.error('[uploadItemImage] 删除文件失败:', unlinkErr);
          }
          return res.status(404).json({
            success: false,
            message: '菜单项不存在或已被删除'
          });
        }
        
        logger.debug(`[uploadItemImage] 菜单项存在，准备更新 image_url 字段，原值: ${menuItem.image_url}，新值: ${imageUrl}`);
        
        // 3. 直接通过数据库查询更新 image_url 字段，避免模型层验证
        const updateQuery = 'UPDATE menu_items SET image_url = ? WHERE id = ? AND deleted_at IS NULL';
        logger.debug(`[uploadItemImage] 执行SQL: ${updateQuery}，参数: [${imageUrl}, ${id}]`);
        
        const updateResult = await db.query(updateQuery, [imageUrl, id]);
        logger.debug(`[uploadItemImage] 直接SQL更新结果:`, updateResult);
        
        if (updateResult.affectedRows === 0) {
          logger.debug(`[uploadItemImage] 错误: 直接SQL更新失败，影响行数为0`);
          // 删除已上传的文件
          logger.debug(`[uploadItemImage] 删除已上传的图片: ${req.file.path}`);
          try {
            fs.unlinkSync(req.file.path);
          } catch (unlinkErr) {
            logger.error('[uploadItemImage] 删除文件失败:', unlinkErr);
          }
          return res.status(500).json({
            success: false,
            message: '更新菜单项图片失败'
          });
        }
        
        // 4. 获取更新后的菜单项（可选，用于返回最新数据）
        const updatedMenuItem = await MenuItem.findById(id);
        logger.debug(`[uploadItemImage] 更新后的菜单项:`, updatedMenuItem ? `image_url=${updatedMenuItem.image_url}` : '未找到');
        
        logger.debug(`[uploadItemImage] 图片上传成功，返回URL: ${imageUrl}`);
        res.status(200).json({
          success: true,
          message: '图片上传成功',
          image_url: imageUrl,
          menu_item: updatedMenuItem
        });
    } catch (err) {
        logger.error('[uploadItemImage] 图片上传失败:', err);
        
        // 删除可能已上传的文件
        if (req.file) {
          logger.debug(`[uploadItemImage] 删除上传失败的图片: ${req.file.path}`);
          try {
            fs.unlinkSync(req.file.path);
          } catch (unlinkErr) {
            logger.error('[uploadItemImage] 删除上传失败的图片时出错:', unlinkErr);
          }
        }
        
        res.status(500).json({
          success: false,
          message: '图片上传失败',
          error: err.message
        });
      }
    }
  ];
  
  /**
   * 批量清空旧的image_url字段
   */
  static async clearOldImageUrls(req, res) {
    try {
      logger.info('[clearOldImageUrls] 开始批量清空旧的image_url字段');
      
      // 直接执行SQL更新
      const updateQuery = 'UPDATE menu_items SET image_url = NULL WHERE deleted_at IS NULL';
      logger.debug(`[clearOldImageUrls] 执行SQL: ${updateQuery}`);
      
      const result = await db.query(updateQuery);
      logger.debug(`[clearOldImageUrls] 更新结果:`, result);
      
      res.status(200).json({
        success: true,
        message: `已清空所有菜单项的图片URL，共影响 ${result.affectedRows} 条记录`,
        affected_rows: result.affectedRows
      });
    } catch (err) {
      logger.error('[clearOldImageUrls] 批量清空失败:', err);
      res.status(500).json({
        success: false,
        message: '批量清空失败',
        error: err.message
      });
    }
  }

  /**
   * 重置菜单项自增ID
   */
  static async resetMenuItemIds(req, res) {
    try {
      logger.info('尝试重置菜单项自增ID...');
      
      // 检查数据库类型
      if (typeof db.query !== 'function') {
        // 模拟数据库
        if (db.resetMenuItemsId) {
          logger.info('使用模拟数据库，调用resetMenuItemsId函数');
          try {
            await db.resetMenuItemsId();
          } catch (mockError) {
            logger.error('模拟数据库重置失败:', mockError);
            return res.status(500).json({
              success: false,
              message: '模拟数据库重置失败',
              error: mockError.message
            });
          }
          logger.info('模拟数据库中菜单项ID已重置');
        } else {
          logger.warn('模拟数据库中未找到resetMenuItemsId函数，跳过重置');
        }
        
        return res.status(200).json({
          success: true,
          message: '菜单项ID重置成功（模拟数据库）'
        });
      }
      
      // 真实数据库
      // 1. 获取当前最大菜单项数量
      const countResult = await db.query('SELECT COUNT(*) as count FROM menu_items WHERE deleted_at IS NULL');
      const itemCount = countResult[0].count;
      logger.info(`当前菜单项数量: ${itemCount}`);
      
      // 2. 重置自增ID为下一个值
      await db.query('ALTER TABLE menu_items AUTO_INCREMENT = 1');
      logger.info('菜单项自增ID已重置为1');
      
      res.status(200).json({
        success: true,
        message: '菜单项ID重置成功',
        current_item_count: itemCount
      });
    } catch (error) {
      logger.error('重置菜单项自增ID失败:', error);
      res.status(500).json({
        success: false,
        message: '重置菜单项ID失败',
        error: error.message
      });
    }
  }
}

module.exports = MenuController;